#!/bin/bash
#本脚本根据kabi白名单，尝试分析名单与模块的关系。

KO_LIST=ko.list
SYM_LIST=sym.list
MODULE_KABI=$1
SYMCOUNT_LIST=symcount.list
KABI_COUNT_LIST=kabi_count.list
KABI_COUNT_SORT=kabi_count.sort
KO_ALL=ko.all

export LC_ALL=C 

get_sym()
{
    echo "获取模块信息"
    echo -n "" > $KO_LIST
    ko_list=(`find -name *.ko | tee -a $KO_LIST`)
    #获取每个模块的符号，然后汇总成表
    echo -n "" > $SYM_LIST
    ko_num=${#ko_list[@]}
    num=0
    a=`bc <<< "$ko_num/10+1"`
    for i in ${ko_list[@]}
    do
        symvers=`modprobe --dump-modversions $i`
        for j in ${symvers[@]}
        do
            #echo "$j" "$i" >> $SYM_LIST
	    echo "$j"
        done
        let num+=1
        if [ `echo "$num%$a" | bc` -eq 0 ]; then
            echo "scale=2;$num/$ko_num*100" | bc | awk -F"." '{print$1"%"}'
        fi
    done
    #sort $SYM_LIST -k 2 -o $SYM_LIST
    echo 100%
    echo 完成
}

sta_data()
{
    IFS=$'\n'
    OLDIFS='$IFS'
    filenum=0
    while read line
    do
        sym_list[$filenum]="$line"
        let filenum+=1
    done < $SYM_LIST

    sym=""
    oldsym=""
    echo -n "" > $SYMCOUNT_LIST
    echo -n "" > $KO_ALL
    tmp=()
    n=1
    sym_list_num=${#sym_list[@]}
    a=`bc <<< "$sym_list_num/100+1"`
    array_i=0
    echo "sta_data()开始。。。"
    #根据汇总的信息生成统计表
    for i in ${sym_list[@]}
    do
        syms=(`echo $i | awk '{print$2"\n"$3}'`)
        sym=${syms[0]}
        kodir=${syms[1]}
        if [ "$sym" = "$oldsym" ]; then
            tmp[$n]="$kodir"
            let n+=1
        else
            echo "$n $oldsym ${tmp[@]:0:$n}" >> $SYMCOUNT_LIST
            let n=1
            tmp[0]="$kodir"
        fi
        echo "$kodir" >> $KO_ALL
        oldsym=$sym
        let array_i+=1
        if [ `echo "$array_i%$a" | bc` -eq 0 ]; then
            echo "scale=2;$array_i/$sym_list_num*100" | bc | awk -F"." '{print$1"%"}'
        fi
    done
    exit
    sed -i '1d' $SYMCOUNT_LIST
    sort -u $KO_ALL -o $KO_ALL
    echo "完成"
}

filter_kabi()
{
    #根据指定kabi白名单筛选
    kabi_list=(`cat $MODULE_KABI | awk '{print$2}'`)
    echo "filter_kabi()开始。。。"
    echo -n "" > $KABI_COUNT_LIST
    for i in ${kabi_list[@]}
    do
        line=`cat $SYMCOUNT_LIST | grep -P '^\S+\s+'$i'\b'`
        if [ -z "$line" ]; then
            echo "0 $i" >> $KABI_COUNT_LIST
        fi
        echo $line >> $KABI_COUNT_LIST
    done
    cat $KABI_COUNT_LIST | sort -hr > $KABI_COUNT_SORT
    echo "完成"
}

get_sym
#sta_data
#filter_kabi
